package galaxies.starRegions;

import galaxies.SpiralStarLocationGenerator;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jme3.math.Vector2f;



public class StarRegionBuilder {
	
	private static final Logger logger = Logger.getLogger(StarRegionBuilder.class.getName());
	
	/*
	 * Creates a series of rectangular regions
	 */
	public ArrayList<StarRegionModel> buildRegions(ArrayList<ArrayList<Integer>> dims) {
		
		logger.log(Level.INFO, "Building star regions");
		
		//find largest and smallest x, y values in dims
		int maxX = 0, maxY = 0, minX = 0, minY = 0;		
		for (ArrayList<Integer> point: dims) {
			if (point.get(0)>maxX)
				maxX = point.get(0);
			else if (point.get(0) < minX)
				minX = point.get(0);
			
			if (point.get(1) > maxY)
				maxY = point.get(1);
			else if (point.get(1) < minY)
				minY = point.get(1);			
		}
		
		/*
		 * Can now define and subdivide a rectangle based on the corners formed by the min, max values in x,y 
		 * directions.
		 * 
		 * Always have a minimum of 4 sectors in any galaxy.  Additional sectors created if these 4 sectors
		 * would be too large.
		 * 
		 * Max sector size = 40x40
		 */
		double xLength = maxX - minX;
		double yLength = maxY - minY;
		double maxRegionSide = 40;
		
		int numSectorsX = (int) Math.ceil(xLength/maxRegionSide);
		int numSectorsY = (int) Math.ceil(yLength/maxRegionSide);
		
		if (numSectorsX < 2)
			numSectorsX = 2;
		
		if (numSectorsY < 2)
			numSectorsY = 2;
		
		logger.log(Level.INFO, "# of X Regions: " + numSectorsX);
		logger.log(Level.INFO, "# of Y Regions: " + numSectorsY);
		
		float xRegionSide = (float) xLength/(float) numSectorsX;
		float yRegionSide = (float) yLength/(float) numSectorsY;
		
		ArrayList<StarRegionModel> regions = new ArrayList<StarRegionModel>();
		ArrayList<Vector2f> points = new ArrayList<Vector2f>();
		
		float startX = minX;
		for (int i = 0; i < numSectorsX; i++) {
			float startY = minY;
			
			for (int j = 0; j < numSectorsY; j++) {
				Vector2f temp1 = new Vector2f(startX, startY);
				Vector2f temp2 = new Vector2f(startX+xRegionSide, startY);
				Vector2f temp3 = new Vector2f(startX+xRegionSide, startY+yRegionSide);
				Vector2f temp4 = new Vector2f(startX, startY+yRegionSide);
				
				points.add(temp1);
				points.add(temp2);
				points.add(temp3);
				points.add(temp4);				
				
				StarRegionModel region = new StarRegionModel(points);
				regions.add(region);
				startY += yRegionSide;
				points.clear();
			}			
			startX+=xRegionSide;
		}
		logger.log(Level.INFO, "Finished building star regions");
		return regions;
	}

}
